from rest_framework import status, permissions
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from django.db import transaction, models
from django.utils import timezone
from .models import MatchmakingQueue
from .serializers import MatchmakingQueueSerializer, JoinMatchmakingSerializer
from .matchmaking_logic import MatchmakingSystem


@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def join_matchmaking(request):
    """加入匹配队列"""
    serializer = JoinMatchmakingSerializer(data=request.data, context={'request': request})
    if serializer.is_valid():
        deck_id = serializer.validated_data['deck_id']
        
        # 检查用户是否已在队列中
        existing_queue = MatchmakingQueue.objects.filter(user=request.user, is_active=True).first()
        if existing_queue:
            return Response({'error': '您已在匹配队列中'}, status=status.HTTP_400_BAD_REQUEST)
        
        with transaction.atomic():
            # 加入队列
            queue_entry = MatchmakingQueue.objects.create(
                user=request.user,
                deck_id=deck_id
            )
            
            # 尝试匹配
            match_result = MatchmakingSystem.find_match(request.user)
            
            if match_result:
                if match_result.get('timeout'):
                    return Response({
                        'error': match_result['message']
                    }, status=status.HTTP_408_REQUEST_TIMEOUT)
                else:
                    return Response({
                        'message': '匹配成功',
                        'game_id': match_result['game_id'],
                        'opponent': match_result['opponent']
                    })
            else:
                return Response({
                    'message': '已加入匹配队列',
                    'queue_id': queue_entry.id,
                    'estimated_wait_time': 30,  # 预估等待时间
                    'matchmaking_rating': queue_entry.matchmaking_rating
                })
    
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def leave_matchmaking(request):
    """离开匹配队列"""
    try:
        queue_entry = MatchmakingQueue.objects.get(user=request.user, is_active=True)
        queue_entry.is_active = False
        queue_entry.save()
        return Response({'message': '已离开匹配队列'})
    except MatchmakingQueue.DoesNotExist:
        return Response({'error': '您不在匹配队列中'}, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET'])
@permission_classes([permissions.IsAuthenticated])
def matchmaking_status(request):
    """获取匹配状态"""
    try:
        queue_entry = MatchmakingQueue.objects.get(user=request.user, is_active=True)
        serializer = MatchmakingQueueSerializer(queue_entry)
        return Response({
            'in_queue': True,
            'queue_data': serializer.data,
            'wait_time': queue_entry.wait_time,
            'matchmaking_rating': queue_entry.matchmaking_rating
        })
    except MatchmakingQueue.DoesNotExist:
        # 检查用户是否被匹配到游戏（不在队列中但可能有新游戏）
        from apps.games.models import Game
        recent_game = Game.objects.filter(
            models.Q(player1=request.user) | models.Q(player2=request.user),
            status__in=['waiting', 'playing'],  # 支持waiting和playing状态
            created_at__gte=timezone.now() - timezone.timedelta(minutes=1)  # 最近1分钟创建的游戏
        ).order_by('-created_at').first()
        
        if recent_game:
            # 用户被匹配到游戏
            opponent = recent_game.player2 if recent_game.player1 == request.user else recent_game.player1
            return Response({
                'in_queue': False,
                'queue_data': None,
                'matched_game': {
                    'game_id': recent_game.id,
                    'opponent': {
                        'id': opponent.id,
                        'nickname': opponent.nickname,
                        'level': opponent.level,
                        'win_rate': opponent.win_rate
                    }
                }
            })
        
        return Response({
            'in_queue': False,
            'queue_data': None
        })


@api_view(['GET'])
@permission_classes([permissions.IsAuthenticated])
def matchmaking_stats(request):
    """获取匹配统计信息"""
    stats = MatchmakingSystem.get_matchmaking_stats()
    return Response(stats)


@api_view(['GET'])
@permission_classes([permissions.IsAuthenticated])
def check_match_result(request):
    """检查匹配结果"""
    from apps.games.models import Game
    
    # 检查用户是否被匹配到游戏（最近1分钟创建的游戏）
    recent_game = Game.objects.filter(
        models.Q(player1=request.user) | models.Q(player2=request.user),
        status__in=['waiting', 'playing'],  # 支持waiting和playing状态
        created_at__gte=timezone.now() - timezone.timedelta(minutes=1)
    ).order_by('-created_at').first()
    
    if recent_game:
        # 用户被匹配到游戏
        opponent = recent_game.player2 if recent_game.player1 == request.user else recent_game.player1
        return Response({
            'matched': True,
            'game_id': recent_game.id,
            'opponent': {
                'id': opponent.id,
                'nickname': opponent.nickname,
                'level': opponent.level,
                'win_rate': opponent.win_rate
            }
        })
    
    return Response({
        'matched': False
    })


@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def cleanup_matchmaking(request):
    """清理过期匹配队列（管理员功能）"""
    if not request.user.is_staff:
        return Response({'error': '权限不足'}, status=status.HTTP_403_FORBIDDEN)
    
    cleaned_count = MatchmakingSystem.cleanup_expired_queues()
    return Response({
        'message': f'清理了 {cleaned_count} 个过期队列',
        'cleaned_count': cleaned_count
    })
